//
//  DULocation.m
//  APP
//
//  Created by duyujin1 on 2021/8/25.
//

#import "DULocation.h"
#import <CoreLocation/CoreLocation.h>
#import "AppDelegate.h"
#import "DUAlert.h"
#import "DUNotification.h"

@interface DULocation()<CLLocationManagerDelegate>
@property(nonatomic,strong)CLLocationManager * manager;
@end

@implementation DULocation

+(DULocation *)locationManager{
    static DULocation * location;
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken, ^{
        location=[[DULocation alloc] init];
    });
    return location;
}

-(instancetype)init{
    if(self=[super init]){
        self.manager=[[CLLocationManager alloc] init];
        self.manager.delegate=self;
    }
    return self;
}

-(void)checkLocationAuthorization{
    //判断系统地位服务是否开启
    if(![CLLocationManager locationServicesEnabled]){
        //引导弹窗
    }
    else{
        if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
            [self.manager requestWhenInUseAuthorization];
        }
    }
}

#pragma mark- delegate

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if(status==kCLAuthorizationStatusAuthorizedWhenInUse){
        [[DUNotification notificatonManager] checkNotificationAuthorization];
        [manager startUpdatingLocation];
    }else if(status==kCLAuthorizationStatusDenied){
        //
        [DUAlert showAlertWithTitle:@"您未开启定位权限，是否前往设置中开启？" detailIfon:nil confirmHandle:^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        } cancelHandle:^{
            exit(0);
//            UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
//            [UIView animateWithDuration:0.5f animations:^{
//                //window.alpha=1;
//                window.frame=CGRectZero;
//            } completion:^(BOOL finished) {
//                exit(0);
//            }];
        }];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //地理信息
    CLLocation *location = [locations firstObject];
    CLGeocoder *coder = [[CLGeocoder alloc] init];
    [coder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //地标信息
    }];
    [self.manager stopUpdatingLocation];
}

@end
